package admin.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.AdsDealModel;
import models.DealModel;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class AdsDealData {
	private static Objectify ofy;

	private static Cache cache = null;

	private static String prefix = "ads_";

	private static boolean isRegisted = false;

	private static ObjectifyOpts opts = null;

	private static void init() {
		if (!isRegisted) {
			try {
				ObjectifyService.register(AdsDealModel.class);
			} catch (Exception e) {

			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {

			}
			opts = new ObjectifyOpts().setSessionCache(true);
			isRegisted = true;
		}
		ofy = ObjectifyService.begin(opts);
	}

	public AdsDealData() {
		init();
	}

	/**
	 * "special" - quảng cáo trang chủ. "top" - quảng cáo menu top. "right" -
	 * quảng cáo menu right.
	 * */
	public static AdsDealModel getByType(String type) {
		init();
		return ofy.query(AdsDealModel.class).filter("type", type).get();
	}

	public static List<DealModel> getListDealByType(String type) {
		init();
		AdsDealModel q = ofy.query(AdsDealModel.class).filter("type", type)
				.get();
		if (q != null) {
			List<DealModel> listResult = new ArrayList<DealModel>();
			for (String dealId : q.getListDealId()) {
				DealModel deal = DealData.getActiveById(dealId);
				if (deal != null) {
					listResult.add(deal);
				}
			}
			return listResult;
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public static void insert(AdsDealModel ads) {
		init();
		if (cache != null) {
			cache.put(prefix + ads.getType(), ads);
		}
		ofy.put(ads);
	}

	public static void delete(AdsDealModel ads) {
		init();
		if (cache != null && cache.containsKey(ads.getType())) {
			cache.remove(prefix + ads.getType());
		}
		ofy.delete(ads);
	}
}
